package com.hgyc.mom.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hgyc.mom.common.constant.CacheConstants;
import com.hgyc.mom.common.exception.BizException;
import com.hgyc.mom.common.redis.RedisCache;
import com.hgyc.mom.common.util.StringUtils;
import com.hgyc.mom.common.util.text.Convert;
import com.hgyc.mom.system.entity.SysConfig;
import com.hgyc.mom.system.mapper.SysConfigMapper;
import com.hgyc.mom.system.service.SysConfigService;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 参数配置Service业务层实现
 *
 * @author fwj
 * @since 2025-05-13
 */
@Slf4j
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements SysConfigService {

    @Autowired
    private RedisCache redisCache;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init()
    {
        log.info("加载系统配置数据！");
        loadingConfigCache();
    }

    @Override
    public void saveConfig(SysConfig sysConfig) {
        SysConfig existConfig = getByKey(sysConfig.getConfigKey());
        if (existConfig != null) {
            throw new BizException("编码已存在");
        } else {
            save(sysConfig);
        }
    }

    @Override
    public void updateConfig(SysConfig sysConfig) {
        SysConfig oldConfig = getById(sysConfig.getId());
        if (!Objects.equals(oldConfig.getConfigKey(), sysConfig.getConfigKey())) {
            SysConfig existKey = getByKey(sysConfig.getConfigKey());
            if (existKey != null) {
                throw new BizException("编码已存在");
            }
        }

        updateById(sysConfig);
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache()
    {
        List<SysConfig> configsList = list();
        for (SysConfig config : configsList)
        {
            redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache()
    {
        Collection<String> keys = redisCache.keys(CacheConstants.SYS_CONFIG_KEY + "*");
        redisCache.deleteObject(keys);
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache()
    {
        clearConfigCache();
        loadingConfigCache();
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey)
    {
        return CacheConstants.SYS_CONFIG_KEY + configKey;
    }

    @Override
    public SysConfig getByKey(String key) {
        LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysConfig::getConfigKey, key);

        return getOne(queryWrapper);
    }

    @Override
    public String selectConfigByKey(String configKey)
    {
        String configValue = redisCache.getString(getCacheKey(configKey));
        if (StringUtils.isNotEmpty(configValue))
        {
            return configValue;
        }

        SysConfig retConfig = getByKey(configKey);
        if (StringUtils.isNotNull(retConfig))
        {
            redisCache.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }
}
